package com.ljph.jfinal.base;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.validate.Validator;

/**
 * Created by yuzhou on 16/8/4.
 */
public abstract class BaseValidator extends Validator {

    public static final String ERROR_KEY = "error";
    public static final String DEFAULT_FAIL_MSG = "后台数据验证出错";

    public void setController(Controller controller) {
        this.controller = (BaseController)controller;
    }

    protected BaseController controller = null;

    public BaseValidator() {
        setShortCircuit(true);
    }

    protected abstract void validate();

    @Override
    protected void validate(Controller c) {
        this.setController(c);
        validate();
    }

    /**
     * 添加出错信息
     * @param errorMessage
     */
    protected void addError(String errorMessage){
        addError(ERROR_KEY, errorMessage);
    }

    protected String getPara() {
        return controller.getPara();
    }

    protected String getPara(String name) {
        return controller.getPara(name);
    }

    protected BaseController setAttr(String name, Object value) {
        controller.setAttr(name, value);
        return controller;
    }

    protected <T> T getAttr(String name) {
        return controller.getAttr(name);
    }

    /**
     * 获取当前的错误信息
     * @return
     */
    protected String getErrMsg() {
        String errMsg = controller.getAttr(ERROR_KEY);
        if(StrKit.isBlank(errMsg)) {
            errMsg = DEFAULT_FAIL_MSG;
        }
        return errMsg;
    }

    @Override
    protected void handleError(Controller c) {
        controller.commonFailJson(getErrMsg());
    }
}
